<?php
/*
 * @Author: zeyudada
 * @Date: 2022-01-12 20:56:36
 * @LastEditTime: 2022-04-11 09:59:12
 * @Description: 管理员AJAX接口
 * @Q Q: zeyunb@vip.qq.com(1776299529)
 * @E-mail: admin@zeyudada.cn
 * 
 * Copyright (c) 2022 by zeyudada, All Rights Reserved. 
 */

include("../include/common.php");
$act = isset($_GET['act']) ? $_GET['act'] : null;
@header('Content-Type: application/json; charset=UTF-8');

switch ($act) {
    case 'login':
        # 管理登录
        if (empty($_POST['name']) || empty($_POST['pass']) || empty($_POST['code'])) json(['code' => "201", 'msg' => '请填好所有字段！']);
        if (strtoupper($_POST['code']) != $_SESSION['code']) {
            unset($_SESSION['code']);
            json(['code' => "201", 'msg' => '验证码错误']);
        }
        $pwd = md5($_POST['pass']);

        if ($config['admin'] == $_POST['name'] && $config['password'] == $pwd) {
            //保存管理员登录状态
            $_SESSION['admin'] = true;

            $DB->query("INSERT INTO `log`(`userid`, `msg`, `ip`, `time`) VALUES (0, '用户" . $_POST['name'] . "成功登录用户后台', '" . getip() . "', '" . date('Y-m-d H:i:s') . "')");

            json(['code' => 200, 'msg' => '登陆成功']);
        } else {
            json(['code' => 201, 'msg' => '账号或密码错误']);
        }
        break;

    case 'set':
        # 修改站点信息
        if ($DB->query("UPDATE `config` SET `sitename` = '{$_POST['sitename']}', `keywords` = '{$_POST['keywords']}', `description` = '{$_POST['description']}', `kfqq` = '{$_POST['kfqq']}', `rank` = '{$_POST['rank']}' WHERE `id` = 1") > 0) json(['code' => 200, 'msg' => '修改成功']);
        else json(['code' => 201, 'msg' => '修改失败']);
        break;

    case 'passwd':
        # 修改管理员密码
        if (empty($_POST['old']) || empty($_POST['new'])) json(['code' => "201", 'msg' => '请填好所有字段！']);

        $old = md5($_POST['old']);
        $pwd = md5($_POST['new']);

        if ($config['password'] == $old) {
            $DB->query("UPDATE `config` SET `password` = '{$pwd}' WHERE `id` = 1");

            json(['code' => 200, 'msg' => '修改成功，新密码：' . $_POST['new']]);
        } else {
            json(['code' => 201, 'msg' => '老密码错误']);
        }
        break;

    case 'getuser':
        # 获取用户列表
        $page = $_GET['page'] - 1;
        $start = $page * $_GET['limit'];
        # 分页
        $users = $DB->getAll("SELECT * FROM `user` limit {$start}," . intval($_GET['limit']));
        $count = $DB->get_row("SELECT count(*) FROM `user`");
        if (!is_array($users)) json(['code' => 203, 'msg' => '获取数据失败！']);
        json(['code' => 0, 'msg' => '获取数据成功！', 'count' => intval(end($count)), 'data' => $users]);
        break;

    case 'deluser':
        # 删除用户
        if (empty($_POST['id'])) json(['code' => "201", 'msg' => '未提交用户ID！']);

        if ($DB->query("DELETE FROM `user` WHERE `id` = " . intval($_POST['id'])) > 0) json(['code' => 200, 'msg' => '删除成功']);
        else json(['code' => 201, 'msg' => '删除失败']);
        break;

    case 'edituser':
        # 修改用户资料
        if ($DB->query("UPDATE `user` SET `name` = '{$_POST['name']}', `gender` = '{$_POST['gender']}', `birthday` = '{$_POST['birthday']}', `tel` = {$_POST['tel']}, `mail` = '{$_POST['mail']}', `qq` = {$_POST['qq']}, `wechat` = '{$_POST['wechat']}', `address` = '{$_POST['address']}' WHERE `id` = " . $_GET['id']) > 0) json(['code' => 200, 'msg' => '修改成功']);
        else json(['code' => 201, 'msg' => '修改失败']);
        break;

    case 'adduser':
        # 添加用户
        if (empty($_POST['name']) || empty($_POST['password'])) json(['code' => "201", 'msg' => '至少提供用户名和密码！']);
        $pwd = md5($_POST['password']);

        if ($DB->query("INSERT INTO `user`(`name`, `password`, `gender`, `birthday`, `tel`, `mail`, `qq`, `wechat`, `address`) VALUES ('{$_POST['name']}', '{$pwd}', '{$_POST['gender']}', '{$_POST['birthday']}', '{$_POST['tel']}', '{$_POST['mail']}', {$_POST['qq']}, '{$_POST['wechat']}', '{$_POST['address']}')") > 0) json(['code' => 200, 'msg' => '添加成功']);
        else json(['code' => 201, 'msg' => '添加失败']);
        break;

    case 'getanswer':
        # 获取回答

        $page = $_GET['page'] - 1;
        $start = $page * $_GET['limit'];
        # 分页
        $users = $DB->getAll("SELECT answer.id,userid,name,gender,time,answer.date,correct FROM `answer` join user on user.id = answer.userid limit {$start}," . intval($_GET['limit']));
        $count = $DB->get_row("SELECT count(*) FROM `answer`");
        if (!is_array($users)) json(['code' => 203, 'msg' => '获取数据失败！']);
        json(['code' => 0, 'msg' => '获取数据成功！', 'count' => intval(end($count)), 'data' => $users]);
        break;

    case 'addque':
        # 添加问题
        if (empty($_POST['title']) || empty($_POST['options1']) || empty($_POST['options2']) || empty($_POST['answer']) || empty($_POST['type'])) json(['code' => "201", 'msg' => '请填好所有字段！']);
        $pwd = md5($_POST['password']);
        if (!is_numeric($_POST['sort']) || (int)$_POST['sort'] < 1) json(['code' => 201, 'msg' => '分类标识必须是一个大于零的整数！']);

        if ($DB->query("INSERT INTO `question`(`sort`, `type`, `title`, `options1`, `options2`, `options3`, `options4`, `answer`, `parse`) VALUES (" . intval($_POST['sort']) . ", '{$_POST['type']}', '{$_POST['title']}', '{$_POST['options1']}', '{$_POST['options2']}', '{$_POST['options3']}', '{$_POST['options4']}', '{$_POST['answer']}', '{$_POST['parse']}')") > 0) json(['code' => 200, 'msg' => '添加成功']);
        else json(['code' => 201, 'msg' => '添加失败']);
        break;

    case 'delque':
        # 删除题目
        if (empty($_POST['id'])) json(['code' => "201", 'msg' => '未提交题目ID！']);

        if ($DB->query("DELETE FROM `question` WHERE `id` = " . intval($_POST['id'])) > 0) json(['code' => 200, 'msg' => '删除成功']);
        else json(['code' => 201, 'msg' => '删除失败']);
        break;

    case 'uploadpic':
        $file_name = $_FILES['file']['name']; //获取缓存区图片,格式不能变
        $type = array("jpg", "gif", 'png', 'bmp', 'jpeg'); //允许选择的图片类型
        $ext = end(explode(".", $file_name));
        if (!in_array($ext, $type)) json(['code' => 202, 'msg' => '不允许的文件后缀']);

        $path = "assets/upload/" . date('YmdHis') . '_' . rand() . '.' . $ext;
        if(move_uploaded_file($_FILES['file']['tmp_name'], ROOT . $path)) json(['code'=>200, 'msg'=>'上传成功', 'data'=>'/'.$path]);
        else json(['code' => 201, 'msg' => '上传失败']);
        break;

    case 'getque':
        # 获取所有题目

        $page = $_GET['page'] - 1;
        $start = $page * $_GET['limit'];
        # 分页
        $filter = empty($_GET['title']) ? '' : " WHERE title LIKE '%{$_GET['title']}%'";
        $sql = "SELECT * FROM `question`{$filter} limit {$start}," . intval($_GET['limit']);
        $users = $DB->getAll("SELECT * FROM `question`{$filter} limit {$start}," . intval($_GET['limit']));
        $count = $DB->get_row("SELECT count(*) FROM `question`{$filter}");
        if (!is_array($users)) json(['code' => 203, 'msg' => '获取数据失败！']);
        json(['code' => 0, 'msg' => '获取数据成功！', 'count' => intval(end($count)), 'data' => $users]);
        break;

    case 'getlog':
        # 获取登录记录

        $page = $_GET['page'] - 1;
        $start = $page * $_GET['limit'];
        # 分页
        $logs = $DB->getAll("SELECT log.id,msg,ip,log.time,name FROM `log` join user on user.id = log.userid limit {$start}," . intval($_GET['limit']));
        $count = $DB->get_row("SELECT count(*) FROM `log`");
        if (!is_array($logs)) json(['code' => 203, 'msg' => '获取数据失败！']);
        json(['code' => 0, 'msg' => '获取数据成功！', 'count' => intval(end($count)), 'data' => $logs]);
        break;

    case 'getsort':
        # 获取分类

        $page = $_GET['page'] - 1;
        $start = $page * $_GET['limit'];
        # 分页
        $users = $DB->getAll("SELECT * FROM `sort` limit {$start}," . intval($_GET['limit']));
        $count = $DB->get_row("SELECT count(*) FROM `sort`");
        foreach ($users as $k => $v) {
            $users[$k]['begin'] = ($v['begin'] > 0) ? date('Y/m/d H:i:s', $v['begin']) : '未开启';
            $users[$k]['end'] = ($v['end'] > 0) ? date('Y/m/d H:i:s', $v['end']) : '未开启';
        }

        if (!is_array($users)) json(['code' => 203, 'msg' => '获取数据失败！']);
        json(['code' => 0, 'msg' => '获取数据成功！', 'count' => intval(end($count)), 'data' => $users]);
        break;

    case 'addsort':
        # 添加分类
        if (empty($_POST['name'])) json(['code' => "201", 'msg' => '请填写完整']);
        if (!empty($_POST['begin']) || !empty($_POST['end'])) {
            if (empty($_POST['begin']) || empty($_POST['end'])) json(['code' => "201", 'msg' => '请填写完整']);
            $begin = strtotime($_POST['begin']) ?: 'null';
            if ($begin == 'null') json(['code' => 201, 'msg' => '答题开始时间异常']);
            $end = strtotime($_POST['end']) ?: 'null';
            if ($begin > $end) json(['code' => 201, 'msg' => '开始时间比结束时间大！']);
            if ($end == 'null') json(['code' => 201, 'msg' => '答题结束时间异常']);
        } else {
            $begin = 'null';
            $end = 'null';
        }

        if ($DB->query("INSERT INTO `sort`(`name`, `begin`, `end`) VALUES ('{$_POST['name']}', $begin, $end)") > 0) json(['code' => 200, 'msg' => '添加成功']);
        else json(['code' => 201, 'msg' => '添加失败']);
        break;

    case 'delsort':
        # 删除分类
        if (empty($_POST['id'])) json(['code' => "201", 'msg' => '未提交分类ID！']);

        if ($DB->query("DELETE FROM `sort` WHERE `id` = " . intval($_POST['id'])) > 0) json(['code' => 200, 'msg' => '删除成功']);
        else json(['code' => 201, 'msg' => '删除失败']);
        break;


    default:
        json(['code' => 500, 'msg' => '方法不存在！']);
        break;
}
